package com.seya.calculite.app;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import interfaces.GPSCallback;

/**
 * Created by Arumugam on 10/17/2014.
 */
public class TimerService extends Service {

    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;
    Handler customHandler = new Handler();
    double currentLon, currentLat, lastLat, lastLon;
    float distanceMeters = 0F, distanceKm = 0F;
    Activity currentActivity;
    SharedPreferences prefs;
    float speed = 0F;
    int totalsecs;
    //double[][] positions;
    static int counter;
    ArrayList<Double> latSeries, lonSeries;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        prefs = this.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME,
                MODE_PRIVATE);
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        counter = 0;

        lastLat = Double.parseDouble(prefs.getString(SplashScreenActivity.START_LATITUDE,""));
        lastLon = Double.parseDouble(prefs.getString(SplashScreenActivity.START_LONGITUDE,""));

        //positions = new double[][2];

        //positions[counter][0] = lastLat;
        //positions[counter][1] = lastLon;

        latSeries = new ArrayList<Double>();
        lonSeries = new ArrayList<Double>();

        latSeries.add(counter, lastLat);
        lonSeries.add(counter, lastLon);

        final LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                counter++;

                if (location.hasSpeed()) {
                    speed = location.getSpeed() * 3.6f;// km/h
                }

                currentLat = location.getLatitude();
                currentLon = location.getLongitude();

                latSeries.add(counter, currentLat);
                lonSeries.add(counter, currentLon);

                Location locationA = new Location("point A");
                /*locationA.setLatitude(lastLat);
                locationA.setLongitude(lastLon);*/
                /*locationA.setLatitude(positions[counter-1][0]);
                locationA.setLongitude(positions[counter-1][1]);*/
                locationA.setLatitude(latSeries.get(counter-1));
                locationA.setLongitude(lonSeries.get(counter-1));

                Location locationB = new Location("point B");
                /*locationB.setLatitude(currentLat);
                locationB.setLongitude(currentLon);*/
                /*locationB.setLatitude(positions[counter][0]);
                locationB.setLongitude(positions[counter][1]);*/
                locationB.setLatitude(latSeries.get(counter));
                locationB.setLongitude(lonSeries.get(counter));

                distanceMeters += locationA.distanceTo(locationB);

                distanceKm = distanceMeters / 1000f;

                lastLat = currentLat;
                lastLon = currentLon;
            }

            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, locationListener);

        customHandler.postDelayed(updateTimerThread, 0);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Runnable updateTimerThread = new Runnable() {
        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - prefs.getLong(SplashScreenActivity
                    .TIMER_SERVICE, SystemClock.uptimeMillis());
            updatedTime = timeSwapBuff + timeInMilliseconds;

            totalsecs = (int) (updatedTime / 1000);
            int secs = totalsecs;
            int mins = secs / 60;
            int hrs = mins / 60;
            mins = mins % 60;
            secs = secs % 60;

            try {
                currentActivity = ((GlobalContext) getApplicationContext()).getCurrentActivity();
                ((TextView) currentActivity.findViewById(R.id.km_view))
                        .setText(String.format("%.2f",distanceKm));
                ((TextView) currentActivity.findViewById(R.id.timing_view_hrs))
                        .setText(String.format("%02d", hrs));
                ((TextView) currentActivity.findViewById(R.id.timing_view_mins))
                        .setText(String.format("%02d", mins));
                ((TextView) currentActivity.findViewById(R.id.timing_view_secs))
                        .setText(String.format("%02d", secs));
            }catch (NullPointerException e){

            }
            customHandler.postDelayed(this, 0);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        timeSwapBuff += timeInMilliseconds;
        customHandler.removeCallbacks(updateTimerThread);
    }

}
